<template>
  <div id="home">
    <div class="map">
      <div id="homemap" ></div>
      <div class="map-info" :class="{'active-bottom':openBottom,'active-left':openLeft}">
        <div class="map-top">
          <div class="search">
            <Row>
              <Col span="6">
                <Select placeholder="省份" v-model="selectProvince" filterable clearable>
                    <Option v-for="(v,i) in provinceList" :value="v.id" :key="`home-callist-select1-${i}-${v.id}`">{{v.name}}</Option>
                </Select>
              </Col>
              <Col span="6">
                <Select placeholder="城市" v-model="selectCity" ref="city" filterable clearable>
                    <Option v-for="(v,i) in cityList" :value="v.id" :key="`home-callist-select2-${i}-${v.id}`">{{v.name}}</Option>
                </Select>

              </Col>
              <Col span="10" :offset="1">
                <Select placeholder="通过司机或手机号码" v-model="searchDriver" filterable clearable>
                   <Option v-for="(v,i) in driverList" :value="v.driverId" :key="`home-driverList-select2-${i}-${v.driverId}`">{{v.driverName}}({{v.tel}})</Option>
                </Select>
              </Col>
            </Row>
          </div>
        </div>
        <div class="map-right">
          <Tree :data="driverTree"></Tree>
        </div>
        <div class="map-bottom"  @click="changeBottom(true)">
          <div class="tool">

            <Button type="text" class="bottom-btn" @click.stop="changeBottom(!openBottom)"><Icon type="chevron-up"></Icon></Button>
          </div>
          <Tabs >
            <TabPane :label="`行驶中司机（${onlineDriver.length}）`" name="1">
              <div class="carinfo">
                <div class="table">
                  <table>
                    <thead>
                      <th width="20%">司机</th>
                      <th width="20%">行驶速度</th>
                      <th width="40%">位置</th>
                      <th width="20%">所属机构</th>
                    </thead>
                    <tbody>
                      <tr v-for="(data,i) in onlineDriver" :key="`home-oc-${i}-${data.id}`">
                        <td>{{data.driverName}}({{data.tel}})</td>
                        <td>{{data.speed}}公里/小时</td>
                        <td>{{data.address}}</td>
                        <td>{{data.orgName}}</td>
                      </tr>
                      <tr v-if="!isDriverLoading&&onlineDriver.length===0">
                        <td colspan="4">暂无数据</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <Spin size="large" fix v-if="isDriverLoading"></Spin>
            </TabPane>
            <TabPane :label="`超速（${overSpeedList.length}）`" name="2">
              <div class="carinfo">
                <div class="table">
                  <table>
                    <thead>
                      <th width="20%">司机</th>
                      <th width="40%">位置</th>
                      <th width="20%">时间</th>
                      <th width="20%">所属机构</th>
                    </thead>
                    <tbody>
                      <tr v-for="(data,i) in overSpeedList" :key="`home-oc-${i}-${data.id}`">
                        <td>{{data.driverName}}({{data.tel}})</td>
                        <td>{{data.address}}</td>
                        <td>{{moment(data.startTime).format('YYYY-MM-DD HH:mm:ss')}}</td>
                        <td>{{data.orgName}}</td>
                      </tr>
                      <tr v-if="!listLoading&&overSpeedList.length===0">
                        <td colspan="5">暂无数据</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <Spin size="large" fix v-if="listLoading"></Spin>
            </TabPane>
            <TabPane :label="`疲劳驾驶（${plList.length}）`" name="3">
              <div class="carinfo">
                <div class="table">
                  <table>
                    <thead>
                      <th width="20%">司机</th>
                      <th width="20%">累计疲劳时间</th>
                      <th width="40%">位置</th>
                      <th width="10%">开始时间</th>
                      <th width="10%">所属机构</th>
                    </thead>
                    <tbody>
                      <tr v-for="(data,i) in plList" :key="`home-oc-${i}-${data.id}`">
                        <td>{{data.driverName}}({{data.tel}})</td>
                        <td>{{time(data.period,1)}}</td>
                        <td>{{data.address}}</td>
                        <td>{{moment(data.startTime).format('YYYY-MM-DD HH:mm:ss')}}</td>
                        <td>{{data.orgName}}</td>
                      </tr>
                      <tr v-if="!listLoading&&plList.length===0">
                        <td colspan="5">暂无数据</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <Spin size="large" fix v-if="listLoading"></Spin>
            </TabPane>
            <TabPane :label="`三急驾驶（${alarmList.length}）`" name="4">
              <div class="carinfo">
                <div class="table">
                  <table>
                    <thead>
                      <th width="20%">司机</th>
                      <th width="20%">行为</th>
                      <th width="40%">位置</th>
                      <th width="10%">时间</th>
                      <th width="10%">所属机构</th>
                    </thead>
                    <tbody>
                      <tr v-for="(data,i) in alarmList" :key="`home-oc-${i}-${data.id}`">
                        <td>{{data.driverName}}({{data.tel}})</td>
                        <td>{{alarmtype[data.type-1]}}</td>
                        <td>{{data.address}}</td>
                        <td>{{moment(data.startTime).format('YYYY-MM-DD HH:mm:ss')}}</td>
                        <td>{{data.orgName}}</td>
                      </tr>
                      <tr v-if="!listLoading&&alarmList.length===0">
                        <td colspan="5">暂无数据</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <Spin size="large" fix v-if="listLoading"></Spin>
            </TabPane>
          </Tabs>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="less" src="@/assets/styles/home.less"></style>
<script>
  import Map                   from '@/plugin/Map'
  import Mapcar                from '@/plugin/Map/Mapcar'
  import Mappath               from '@/plugin/Map/Mappath'
  import {mapState,mapActions,mapMutations} from 'vuex'
  import moment                from 'moment'
  import unit                  from '@/util/unit'
  import simg                  from '@/assets/images/mapIcons/start.png'
  import {getLocation} from '@/plugin/Map/Mapaddress'
  export default {
    data(){
      return {
        map:null,
        zoom:11,
        openBottom:false,
        openLeft:true,
        selectProvince:null,
        selectProvinceName:null,
        openBottom:true,
        selectCity:null,
        alarmtype:['急加速','急减速','左转弯','右转弯','超速'],
        mapmarker:{},
        selectDriver:{},
        selectTrack:{},
        searchDriver:null,
        timer:null,
        isfirst:false
      };
    },
    mounted(){
      this.map = new Map('homemap', {
          zoom:this.zoom
      });

      this.timer = setTimeout(this.reftimer,30000);
    },
    destroyed(){
      clearTimeout(this.timer);
    },
    watch:{
      searchDriver(id){
        this.openDriver(id);
      },
      async selectProvince(id){
        this.selectCity = null;
        this.$refs.city.clearSingleSelect();
        this.changeCityList([]);
        if(!id)return;
        this.loadCityList(id);
        let p = this.provinceList.filter(v=>{
          return v.id === id;
        })[0];

        let loc = await getLocation(p.name);
        this.map.setZoomAndCenter(11,[loc.lng,loc.lat]);
      },
      async selectCity(id){
        if(id){
          let p = this.cityList.filter(v=>{
            return v.id === id;
          })[0];

          let loc = await getLocation(this.selectProvinceName+p.name);
          this.map.setZoomAndCenter(11,[loc.lng,loc.lat]);
        }

      },
      driverList(){
        this.driverList.forEach(v=>{
          if(this.mapmarker[v.driverId])
            this.mapmarker[v.driverId].remove();
         this.mapmarker[v.driverId] = new Mapcar({
            map:this.map,
            gps:v,
            isWindow:true,
            info:v,
            winopts:{
              openPath:this.openPath
            }
          });
        });
        if(!this.isfirst){
          this.map.setFitView();
          this.isfirst = true;
        }
      }
    },
    computed:{
      ...mapState('base',['userinfo']),
      ...mapState('home',['driverList','provinceList','cityList','listLoading','plList','isDriverLoading','overSpeedList','alarmList']),
      onlineDriver(){
        return this.driverList.filter(v=>{
          return v.status;
        });
      },
      driverTree(){
        let orgs = {},res=[],org = this.userinfo.org;
        this.userinfo.lowerOrgs.forEach(v=>{
          orgs[v.id] = {
            title:v.orgName,
            type:1,
            data:v,
            num:0,
            expand:true,
            children:[]
          };
          if(v.id === org.id){
            res.push(orgs[v.id]);
          }
        });
        Object.values(orgs).forEach(v=>{
          if(orgs[v.data.parentId])
            orgs[v.data.parentId].children.push(v);
        });

        this.driverList.forEach(v=>{
          if(orgs[v.orgId]){
            orgs[v.orgId].children.push({
              num:1,
              title:v.driverName,
              data:v,
              render:(h,{data})=>{
                return h('span',{
                  class:{
                    'tree-driver':true,
                    online:!!data.data.status,
                    action:this.selectDriver.id === v.driverId
                  },
                  on:{
                    click:()=>{
                      this.selectDriver = {
                        mk:this.mapmarker[v.driverId],
                        data:v,
                        id:v.driverId
                      }
                      this.openDriver();
                    }
                  }
                },data.title);
              }
            });
          }
        })

        this.sumDriver(res[0]);

        return res;
      }
    },
    methods:{
      moment,
      time:unit.time,
      ...mapActions('home',['loadCityList','loadTrack','loadDriverList']),
      ...mapMutations('home',['changeCityList']),
      addStart(obj){
        let lnglat = [obj.lng,obj.lat];
        return new AMap.Marker({
          map:this.map,
          icon:new AMap.Icon({
                imageSize:new AMap.Size(32/1.5,53/1.5),
                size: new AMap.Size(32, 53),
                image: simg
            }),
          position:lnglat
        })
      },
      async reftimer(){
        this.loadDriverList();
        if(this.selectTrack.info){
          let res = await this.loadTrack({driverId:this.selectTrack.info.driverId,sTime:this.selectTrack.res[this.selectTrack.res.length-1].locTime});

          res = [...this.selectTrack.res,...res.data.data];
          this.selectTrack.res = res;
          if(this.selectTrack.line){
            this.selectTrack.line.setPath(res.map(v=>{
              return new AMap.LngLat(v.lng,v.lat);
            }));
          }else{
            this.selectTrack.line = res.length?new AMap.Polyline({
              map:this.map,
              strokeColor:"#02c2d7",
              strokeWeight:5,
              path:res.data.data.map(v=>{
                return new AMap.LngLat(v.lng,v.lat);
              })
            }):null
          }
        }
        this.timer = setTimeout(this.reftimer,30000);
      },
      async openPath(info,mc){
        if(mc.isOpenpath){
          if(this.startmk){
            this.startmk.setMap(null);
            this.startmk = null;
          }
          if(this.selectTrack.line){
            this.selectTrack.line.setMap(null);
            this.selectTrack = {};
          }
          mc.closePath();
        }else{
          let res = await this.loadTrack({driverId:info.driverId});
          if(this.startmk){
            this.startmk.setMap(null);
            this.startmk = null;
          }
          if(this.selectTrack.line){
            this.selectTrack.line.setMap(null);
            this.selectTrack = {};
          }
          mc.openPath();
          if(res.data.data){
            mc.isOpenpath = true;
            this.startmk = res.data.data[0]?this.addStart(res.data.data[0]):null;

            this.selectTrack = {
              info:info,
              res:res.data.data||[],
              line:res.data.data.length?new AMap.Polyline({
                map:this.map,
                strokeColor:"#02c2d7",
                strokeWeight:5,
                path:res.data.data.map(v=>{
                  return new AMap.LngLat(v.lng,v.lat);
                })
              }):null
            }
          }
        }

      },
      openDriver(id){
        let mk;
        if(id){
          mk = this.mapmarker[id];
        }else{
          mk = this.selectDriver.mk;
        }
        if(mk.isExist){
          mk.openWindow();
          mk.center();
        }else{
          this.$Message.warning('该用户没有上报GPS');
        }

      },
      changeBottom(v){
        this.openBottom = v;
      },
      sumDriver(obj){
        if(obj.children){
          let num = 0;
          obj.children.forEach(v=>{
            num += this.sumDriver(v);
          })
          obj.num += num;
          obj.title = `${obj.title} ( ${obj.num}人 )`;
        }
        return obj.num;
      }
    }
  }
</script>
